import log from '../log/log.js';

let tag = 'favorite-manager';

// 从本地存储获取收藏列表
function getFavoritesFromStorage() {
	try {
		const favorites = uni.getStorageSync('favoriteProducts');
		return favorites ? JSON.parse(favorites) : [];
	} catch (e) {
		log.error(tag, "无法从本地存储中获取收藏内容:", e);
		return [];
	}
}

// 收藏的商品ID列表
var favoriteProductIds = getFavoritesFromStorage();

export default {
	// 添加收藏
	addFavorite: function(productId) {
		log.info(tag, `addFavorite: ${productId}`);
		if (!favoriteProductIds.includes(productId)) {
			favoriteProductIds.push(productId);
			this.saveFavorites();
		}
	},
	
	// 取消收藏
	removeFavorite: function(productId) {
		log.info(tag, `removeFavorite: ${productId}`);
		const index = favoriteProductIds.indexOf(productId);
		if (index > -1) {
			favoriteProductIds.splice(index, 1);
			this.saveFavorites();
		}
	},
	
	// 切换收藏状态
	toggleFavorite: function(productId) {
		if (this.isFavorite(productId)) {
			this.removeFavorite(productId);
			return false;
		} else {
			this.addFavorite(productId);
			return true;
		}
	},
	
	// 检查是否已收藏
	isFavorite: function(productId) {
		return favoriteProductIds.includes(productId);
	},
	
	// 获取所有收藏的商品ID
	getFavorites: function() {
		return [...favoriteProductIds];
	},
	
	// 保存到本地存储
	saveFavorites: function() {
		try {
			uni.setStorageSync('favoriteProducts', JSON.stringify(favoriteProductIds));
			log.info(tag, "收藏内容已保存至本地存储");
		} catch (e) {
			log.error(tag, "无法将收藏内容保存到本地存储:", e);
		}
	},
	
	// 清空所有收藏
	clearAll: function() {
		log.info(tag, "clearAll");
		favoriteProductIds = [];
		try {
			uni.removeStorageSync('favoriteProducts');
			log.info(tag, "所有收藏内容已经清除");
		} catch (e) {
			log.error(tag, "收藏内容清除失败了:", e);
		}
	}
}
